package com.proxy.autoclick.checker.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.proxy.autoclick.common.valueobject.Proxy;

/**
 * Threadpool for management thread.
 *
 */
@Named
public class ThreadPool {
	
	private static final Logger LOGGER = Logger.getLogger(ThreadPool.class);
	
	@Inject
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	/**
	 * Create thread pool, create a couple threads, pass proxy object and submit task to pool.
	 * When all the thread finish the return.
	 * @param httpclient
	 * @param myProxyList
	 * @throws Exception
	 */
	public void start(HttpClient httpclient,List<Proxy> myProxyList) throws Exception {

		/*ThreadPoolExecutor threadPool = new ThreadPoolExecutor(Constants.CORE_POOL_SIZE, Constants.MAX_POOL_SIZE, Constants.KEEP_ALIVE_TIME,
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(Constants.QUEUESIZE),
				new ThreadPoolExecutor.CallerRunsPolicy());*/
//		ExecutorService threadPool = Executors.newFixedThreadPool(5);

		List<ThreadPoolTask> threadPoolTaskList = new ArrayList<ThreadPoolTask>();
		for (Proxy myProxy : myProxyList) {
			threadPoolTaskList.add(new ThreadPoolTask(httpclient,myProxy));
			/*try {
//				System.out.println("\r\nCreate task and submit to thread pool for proxy：" + httpHost);
			} catch (Exception e) {
				e.printStackTrace();
			}*/
		}
		threadPoolTaskExecutor.getThreadPoolExecutor().invokeAll(threadPoolTaskList);
	}
	
	public void stop()
	{
		// Wait for threads to finish off.
		threadPoolTaskExecutor.shutdown();
		try {
			// Wait for everything to finish.
			while (!threadPoolTaskExecutor.getThreadPoolExecutor().awaitTermination(2, TimeUnit.SECONDS)) {
//				System.out.println("Awaiting completion of threads.");
				Thread.sleep(100);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
}
